package cn.texous.dns.util;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * insert description here
 *
 * @author Showa.L
 * @since 2019/7/5 11:21
 */
@Slf4j
public class FileUtils {

    public static final InputStream getFromClassPath(String fileName) {
        return FileUtils.class.getClassLoader().getResourceAsStream(fileName);
    }

    /***/
    public static final String getFromClassPath2String(String fileName) {
        BufferedReader br = null;
        InputStream inputStream = null;
        String result = null;
        try {
            inputStream = getFromClassPath(fileName);
            br = new BufferedReader(new InputStreamReader(inputStream));
            String lineStr = null;
            StringBuilder sb = new StringBuilder();
            while ((lineStr = br.readLine()) != null) {
                sb.append(lineStr).append("\n");
            }
            sb.delete(sb.lastIndexOf("\n"), sb.length());
            result = sb.toString();
        } catch (Exception e) {
            log.error("读取文件失败", e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
            if (br != null) {
                try {
                    br.close();
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
        }

        return result;
    }

    public static void main(String[] args) {
        System.out.println(getFromClassPath2String("templates/mail.html"));
    }

}
